#pragma once

namespace Lin {
	template<class T>
	struct list_node
	{
		list_node<T>* _next;
		list_node<T>* _prev;
		T _val;

		list_node(const T& val = T()) 
			: _next(nullptr)
			, _prev(nullptr)
			, _val(val)
		{
		} 
	};
	
	template<class T,class Ref,class  ptr>
	struct __list_iterator {
		typedef list_node<T> node;
		typedef __list_iterator<T, Ref,ptr> self;
		node* _node;

		__list_iterator(node* node)
			:_node(node)
		{
		}

		Ref operator*() {
			return _node->_val;
		}

		ptr operator->() {
			return &_node->val;
		}

		self& operator++() {
			_node = _node->_next;
			return *this;
		}	

		self& operator--() {
			_node = _node->_prev;
			return *this;
		}

		self& operator++(int) {
			self tmp(*this);
			_node = _node->_next;
			return tmp;
		}

		self& operator--(int) {
			self tmp(*this);
			_node = _node->_prev;
			return tmp;
		}

		bool operator!=(const self& it) const {
			return _node != it._node;
		}

		bool operator==(const self& it) const {
			return _node == it._node;
		}

	};

	template<class T>
	class list {
		typedef list_node<T> node;
	public:
		typedef __list_iterator<T,T&,T*> iterator;
		typedef __list_iterator<T, const T&,const T*> const_iterator;

		iterator begin() {
			return _head->_next;
		}

		iterator end() {
			return _head;
		}

		const_iterator begin() const {
			return _head->_next;
		}

		const_iterator end() const {
			return _head;
		}

		list() {
			_head = new node();
			_head->_prev = _head;
			_head->_next = _head;
			_size = 0;
		}

		list(const list<T>& x) {
			_head = new node();
			_head->_prev = _head;
			_head->_next = _head;
			_size = 0;

			for (auto& e : x) {
				push_back(e);
			}
		}

		void swap(list<T>& it){
			std::swap(_head, it._head);
			std::swap(_size, it._size);
		}

		list<T>& operator=(list<T> it) {
			swap(it);
			return *this;
		}

		~list() {
			clear();
			delete _head;
			_head = nullptr;
		}

		void push_back(const T& x) {
			node* tail = _head->_prev;
			node* newnode = new node(x);

			tail->_next = newnode;
			newnode->_prev = tail;
			newnode->_next = _head;
			_head->_prev = newnode;
			_size++;
		}

		void push_front(const T& x) {
			insert(begin(), x);
		}

		void pop_back() {
			erase(--end());
		}

		void pop_front() {
			erase(begin());
		}

		iterator insert(iterator pos, const T& x) {
			node* newnode = new node(x);
			node* cur = pos._node;
			node* prev = cur->_prev;

			prev->_next = newnode;
			newnode->_prev = prev;
			cur->_prev = newnode;
			newnode->_next = cur;
			_size++;
			return newnode;
		}

		iterator erase(iterator pos) {
			node* cur = pos._node;
			node* prev = cur->_prev;
			node* next = cur->_next;


			prev->_next = next;
			next->_prev = prev;

			delete cur;
			_size--;
			return next;
		}

		void clear() {
			iterator it = begin();
			while (it != end()) {
				it = erase(it);
			}
			_size = 0;
		}

		size_t size() {
			return _size;
		}

	private:
		node* _head;
		size_t _size;
	};
}

